package de.lmu.ifi.pst.uwejsf.framework;

import java.util.List;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;

public class OGNLIndexRowPropertyResolver implements IndexRowPropertyResolver {

	private Expression expression;

	@Override
	public Expression getExpression() {
		return expression;
	}

	@Override
	public Object getValue(ExpressionContextProvider contextProvider,
			String nodeName, String propertyName, Object contentObject,
			int rowIndex) {
		if (expression == null)
			return null;
		if (expression.getExpression() == null)
			return null;

		ScriptEngine engine = contextProvider.getScriptEngineByName("ognl");
		ScriptContext scriptContext = contextProvider
				.createScriptContext(contentObject);
		scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put(
				"uweItemIndex", rowIndex);
		IndexBean indexBean = (IndexBean) ExpressionHelpers.resolveValue("#{"
				+ UWEHelpers.firstToLower(nodeName) + "}");
		List<?> indexList = indexBean.getUWEContent();
		scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put(
				"uweItemList", indexList);
		Object result = null;
		try {
			result = engine.eval(expression.getExpression(), scriptContext);
		} catch (Exception e) {
			throw new NavigationException("Couldn't evaluate OGNL script: "
					+ expression.getExpression(), e);
		}
		return result;
	}

	@Override
	public void setExpression(Expression expression) {
		this.expression = expression;

	}
}
